<template>
	<!-- 手机验证弹窗 -->
	<up-popup :show="showBindPhonePopup" :closeable="true" @close="showBindPhonePopup = false" mode="bottom"
		:round="16">
		<view class="popup-container">
			<view class="popup-title">手机验证</view>
			<view class="popup-content">
				<u-form :model="verifyForm" :rules="verifyRules" ref="verifyFormRef">
					<view class="verification-info">
						手机号验证码已发送至 <text class="phone-highlight">{{ getMaskedNumber(phoneNumber) }}</text> 内
					</view>
					<u-form-item prop="verificationCode" class="form-item">
						<u-input v-model="verifyForm.verificationCode" placeholder="请输入验证码" type="number" maxlength="6"
							class="verification-input" />
					</u-form-item>
					<view class="time-info">
						10分钟后失效
						<text class="resend-link" @click="resendVerificationCode">重新发送验证码</text>
					</view>
				</u-form>
			</view>
			<button class="confirm-button" @click="confirmBindPhone">确定</button>
		</view>
	</up-popup>
	   <!-- 设置密码弹窗 -->
    <up-popup
      :show="showSetPasswordPopup"
      :closeable="true"
      @close="showSetPasswordPopup = false"
      mode="bottom"
      :round="16"
    >
      <view class="popup-container">
        <view class="popup-title">设置密码</view>
        <view class="popup-content">
          <u-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef">
            <view class="password-item">
              <view class="password-label">新密码</view>
              <u-form-item prop="newPassword" class="form-item">
                <u-input
                  v-model="passwordForm.newPassword"
                  placeholder="请输入新密码"
                  password
                  class="password-input"
                />
              </u-form-item>
            </view>
            <view class="password-item">
              <view class="password-label">再次确认密码</view>
              <u-form-item prop="confirmPassword" class="form-item">
                <u-input
                  v-model="passwordForm.confirmPassword"
                  placeholder="请输入新密码"
                  password
                  class="password-input"
                />
              </u-form-item>
            </view>
          </u-form>
        </view>
        <button class="confirm-button" @click="confirmSetPassword">确定</button>
      </view>
    </up-popup>
</template>

<script setup>
import { ref, reactive, watch } from "vue";
import { onShow } from '@dcloudio/uni-app'
import { getUpdateCode, checkCode, setNewPwd } from '@/api/auth'
// 控制弹窗显示
const showBindPhonePopup = ref(false);
const showSetPasswordPopup = ref(false);
const verifyFormRef = ref(null);
const passwordFormRef = ref(null);
// 表单数据
const verifyForm = reactive({
	verificationCode: ''
});
const passwordForm = reactive({
  newPassword: '',
  confirmPassword: ''
});
const verifyRules = {
	verificationCode: [
		{ required: true, message: '请输入验证码', trigger: 'blur' },
		{ pattern: /^\d{6}$/, message: '请输入有效的6位数字验证码', trigger: 'blur' }
	]
};
const passwordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};
// 显示的手机号
const phoneNumber = ref('151****0012');
const getMaskedNumber = (phone) => {
	return phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');
};
const props = defineProps({
	showBindPhonePopup: {
		type: Boolean,
		default: false
	},
	phoneNumber: {
		type: String,
		default: ''
	}
})

// 定义事件，用于向父组件传递showBindPhonePopup的变化
const emit = defineEmits(['update:showBindPhonePopup', 'verify-success'])


watch(() => props.showBindPhonePopup, (newVal) => {
	showBindPhonePopup.value = newVal;
	phoneNumber.value = props.phoneNumber;
	if(newVal){
		// 重置手机验证表单
		if (verifyFormRef.value) {
			verifyFormRef.value.resetFields();
		}
	}
})
console.log(props)
// 监听组件内部showBindPhonePopup值的变化，回传给父组件
watch(showBindPhonePopup, (newVal) => {
	emit('update:showBindPhonePopup', newVal);
})
watch(() => props.phoneNumber, (newVal) => {
	console.log("newVal", newVal)
	phoneNumber.value = newVal;
})

// 重新发送验证码
const resendVerificationCode = async () => {
	const res = await getUpdateCode(phoneNumber.value).catch(error => {
		uni.showToast({
			title: '获取验证码失败',
			icon: 'none'
		});
		console.log(error)
	});
	if (res.code === 200) {
		uni.showToast({
			title: '验证码已重新发送',
			icon: 'success'
		});
	} else {
		console.log(res)
		uni.showToast({
			title: res.msg,
			icon: 'none'
		});
	}
};
// 确认手机验证
const confirmBindPhone = () => {
	verifyFormRef.value.validate()
		.then(async () => {
			const res = await checkCode(phoneNumber.value, verifyForm.verificationCode).catch(e => {
				console.log(e)
				uni.showToast({
					title: '验证失败',
					icon: 'none'
				})
			})
			if (res.code === 200) {
				uni.showToast({
					title: '验证成功',
					icon: 'success'
				});
				phoneNumber.value = '';
				verifyForm.verificationCode = '';
				// 验证成功后关闭手机验证弹窗
				showBindPhonePopup.value = false;
				// 打开设置密码弹窗
				showSetPasswordPopup.value = true;
				// 重置设置密码表单
				passwordForm.newPassword = '';
				passwordForm.confirmPassword = '';
				uni.showToast({
					title: '手机验证成功，请设置密码',
					icon: 'success'
				});
			} else {
				console.log('验证失败');
				uni.showToast({
					title: '验证失败',
					icon: 'none'
				});
			}
		})
		.catch(errors => {
			// 表单验证失败
			console.log('表单验证失败：', errors);
		});
};
// 确认设置密码
const confirmSetPassword = () => {
  passwordFormRef.value.validate()
    .then(async () => {
      const res = await setNewPwd({
        password: passwordForm.newPassword
      })
      .catch(e => {
        console.log(e)
        uni.showToast({
          title: '设置密码失败',
          icon: 'none'
        })
      })
      if(res.code === 200){
        // 设置密码成功后关闭弹窗
        showSetPasswordPopup.value = false;
        uni.showToast({
          title: '密码设置成功',
          icon: 'success'
        });
      }else{
        uni.showToast({
          title: res.msg,
          icon: 'none'
        });
      }
      
    })
    .catch(errors => {
      // 表单验证失败
      console.log('表单验证失败：', errors);
    });
};
</script>

<style lang="scss" scoped>
/* 弹窗样式 */
.popup-container {
	padding: 30rpx;
	background-color: #ffffff;
	border-radius: 16rpx 16rpx 0 0;
}

.popup-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #303133;
	text-align: center;
	margin-bottom: 30rpx;
}

.popup-content {
	margin-bottom: 30rpx;
}

.verification-info {
	font-size: 28rpx;
	color: #303133;
	margin-bottom: 20rpx;
}

.phone-highlight {
	color: #2979ff;
	font-weight: 500;
}

.verification-input {
	width: 100%;
	height: 80rpx;
	border: 1rpx solid #e4e7ed;
	border-radius: 8rpx;
	padding: 0 20rpx;
	margin-bottom: 10rpx;
}
/* 适配验证码按钮 */
.u-form-item {
  position: relative;
}

.u-form-item__right {
  flex: 0 0 auto;
 	margin-left: 10px;
}

.form-item {
  margin-bottom: 30rpx;
  position: relative;
}
/* 表单验证错误提示样式 */
.u-form-item__error-message {
	font-size: 24rpx;
	color: #f56c6c;
	margin-top: 8rpx;
	margin-bottom: 20rpx;
}

.time-info {
	font-size: 24rpx;
	color: #909399;
	display: flex;
	justify-content: center;
	align-items: center;
	margin-top: 20rpx;
	margin-bottom: 30rpx;
}

.resend-link {
	color: #2979ff;
}

.password-item {
	margin-bottom: 20rpx;
}

.password-label {
	font-size: 28rpx;
	color: #303133;
	margin-bottom: 10rpx;
}

.password-input {
	width: 100%;
	height: 80rpx;
	border: 1rpx solid #e4e7ed;
	border-radius: 8rpx;
	padding: 0 20rpx;
	margin-bottom: 10rpx;
}

.confirm-button {
	width: 100%;
	height: 90rpx;
	background-color: #2979ff;
	color: #ffffff;
	font-size: 32rpx;
	border-radius: 45rpx;
	margin-top: 20rpx;
}

/* 适配底部弹窗的遮罩层 */
.u-popup__mask {
	background-color: rgba(0, 0, 0, 0.5);
}
</style>